package app

import (
	"common/config"
	"common/discovery"
	"common/logs"
	"context"
	"fmt"
	"gate/router"
	"google.golang.org/grpc"
	"os"
	"os/signal"
	"syscall"
)

// Run 服务启动
func Run(ctx context.Context) error {
	// 1. 创建 gRPC 服务、 Etcd 服务
	server := grpc.NewServer()
	register := discovery.NewEtcdRegister()
	go func() {
		// 2. 启动 web 服务
		r := router.RegisterRouter()
		if err := r.Run(fmt.Sprintf(":%d", config.Conf.HttpPort)); err != nil {
			logs.Fatal("gate server run error:%v", err)
		}
	}()
	stop := func() {
		server.Stop()
		register.Close()
		logs.Info("stop app finish.")
	}
	// 3. 优雅启停
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGHUP)
	select {
	case <-ctx.Done():
		stop()
	case s := <-c:
		switch s {
		case syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT:
			logs.Warn("user app quit.")
			stop()
		case syscall.SIGHUP:
			logs.Warn("hang up!! user app quit.")
			stop()
		}
	}
	return nil
}
